package com.example.pei.ithinklearnt.view.activity;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.dd.processbutton.iml.ActionProcessButton;
import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.Config;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.present.LoginPresent;
import com.example.pei.ithinklearnt.present.LoginPresentImp;
import com.example.pei.ithinklearnt.utils.thirdpartyUtils.AccessTokenKeeper;
import com.example.pei.ithinklearnt.utils.thirdpartyUtils.SinaUsersApi;
import com.example.pei.ithinklearnt.utils.thirdpartyUtils.TencentUtil;
import com.example.pei.ithinklearnt.view.base.BaseActivity;
import com.example.pei.ithinklearnt.view.interfaces.LoginInterface;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;


import org.json.JSONException;
import org.json.JSONObject;


import butterknife.OnClick;
import cn.bmob.sms.BmobSMS;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.example.pei.ithinklearnt.utils.MyUtils.isAllSpace;


public class Login_Activity extends BaseActivity implements LoginInterface,View.OnClickListener{
    private CheckBox checkBox_displayPassword;
    private EditText editText_passWord;
    private EditText editText_userName;

    private LoginPresent loginPresent;
    private Button btnForgetPassword;

    private ActionProcessButton button_login;

    private boolean isUserNameIn,isPassWdIn; //判断是否输入了用户名和密码

    /**
     * 新浪登录
     */
    private Oauth2AccessToken mAccessToken;
    private SsoHandler mSsoHandler;
    private AuthInfo authInfo;
    private SinaUsersApi mUsersAPI;
    /**
     * 腾讯登录
     */
    private static Tencent mTencent;
    private static boolean isServerSideLogin = false;
    private static com.tencent.connect.UserInfo mInfo;


    private String id;  //第三方登录获得的id
    private String name; //第三方登录获取的用户名（昵称
    private String headUrl; //第三方登录获得的头像地址
    private int sex; //第三方登录获得的性别  1男 0女

    private  BmobUser.BmobThirdUserAuth thirdUserAuth;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_);
        findWidgets();

        Bmob.initialize(AppApplication.getContext(), "43085233ef109100a09bc24120eb2c06");
        BmobSMS.initialize(AppApplication.getContext(),"43085233ef109100a09bc24120eb2c06");

        loginPresent=new LoginPresentImp(this);
        loginPresent.getCurrentUser();   //检测是否有当前用户登录缓存

        /**
         * 新浪登录
         */


        /**
         * 腾讯登录
         */
        mTencent = Tencent.createInstance(Config.TENCENT_APP_ID, getApplicationContext());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode,resultCode,data,loginListener);
        }else if (mSsoHandler != null) {
            // SSO 授权回调
            // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }



    }

    //微信登录
    @OnClick(R.id.ig_bu02)
    void login_weixin(){
        toast("敬请期待 ￣▽￣");
    }
    //新浪账号登录
    @OnClick(R.id.ig_bu03)
    void login_sina(){
        authInfo = new AuthInfo(this, Config.SINA_APP_KEY,
                Config.SINA_REDIRECT_URL, Config.SINA_SCOPE);  //软件认证
        mSsoHandler = new SsoHandler(Login_Activity.this,authInfo);
        mSsoHandler.authorize(new SelfWbAuthListener() );

    }

    public void loginWithAuth(final BmobUser.BmobThirdUserAuth authInfo){
        BmobUser.loginWithAuthData(authInfo, new LogInListener<JSONObject>() {
            @Override
            public void done(final JSONObject jsonObject, BmobException e) {
                if(e==null){
                    final UserInfo currentUser=BmobUser.getCurrentUser(UserInfo.class);
                    currentUser.setNickName(name);
                    currentUser.setUsername(name+"_"+sex);
                    //如果头像为空才赋值，否则每次自己设置的头像都会被覆盖
                    if(currentUser.getHeadFileUrl()==null||currentUser.getHeadFileUrl().equals("")){
                        currentUser.setHeadFileUrl(headUrl);
                    }

                    currentUser.setSex(sex);
                    currentUser.setBirthDay("1999-12-12");  //默认生日
                    currentUser.setUserType(1);             //普通权限
                    currentUser.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if(e==null){
                                //更新当前用户
                                AppApplication.setCurrentUser(currentUser);
                                Intent intent = new Intent(Login_Activity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }else{
                                //注册失败,应该删除此记录
                                currentUser.delete(new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                    }
                                });
                                toast("注册失败，请重试!");
                            }
                        }
                    });

                }else{
                    toast("第三方登陆失败："+e.getMessage());
                }
            }
        });
    }

    private class SelfWbAuthListener implements WeiboAuthListener{
        @Override
        public void onComplete(final Bundle bundle) {

            mAccessToken  = Oauth2AccessToken.parseAccessToken(bundle);;
            if (mAccessToken.isSessionValid()) {
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(Login_Activity.this, mAccessToken);
                toast("授权成功");

                mUsersAPI = new SinaUsersApi(Login_Activity.this, Config.SINA_APP_KEY, AccessTokenKeeper.readAccessToken(Login_Activity.this));

                //调用Bmob提供的授权登录方法进行微博登陆，登录成功后，你就可以在后台管理界面的User表中看到微博登陆后的用户啦
                String token = mAccessToken.getToken();
                String expires = String.valueOf(mAccessToken.getExpiresTime());
                String uuid = mAccessToken.getUid();
                long uid = Long.parseLong(uuid);


                // Log.i("smile", "微博授权成功后返回的信息:token = "+token+",expires ="+expires+",uid = "+uid);
                thirdUserAuth = new BmobUser.BmobThirdUserAuth(BmobUser.BmobThirdUserAuth.SNS_TYPE_WEIBO,token, expires,uuid);
                mUsersAPI.show(uid, mListenermListener);

            }else{
                toast("授权失败:"+bundle.getString("code", ""));
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(Login_Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            toast("取消授权");
        }

        //实现异步请求接口回调，并在回调中直接解析 User 信息
        private RequestListener mListenermListener = new RequestListener() {
            @Override
            public void onComplete(String s) {
                if (!TextUtils.isEmpty(s)) {  //如果不为空

                    try {JSONObject
                         jsonObject = new JSONObject(s);

                        id = jsonObject.optString("id", "");
                        name  = jsonObject.optString("name",    "");
                        headUrl  = jsonObject.optString("avatar_hd", "");
                        sex = (jsonObject.optString("gender", "").equals("m")?1:0);

                        loginWithAuth(thirdUserAuth);
                    } catch (JSONException ee) {
                        ee.printStackTrace();

                    }

                }
            }
            @Override
            public void onWeiboException(WeiboException e) {
                toast(e.getMessage());
            }
        };
    }

    //qq登录
    @OnClick(R.id.ig_bu01)
    void login_tencent(){
        mTencent.logout(this);
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", loginListener);
            isServerSideLogin = false;
        }

    }
    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);

        }
    };
    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            thirdUserAuth = new BmobUser.BmobThirdUserAuth(BmobUser.BmobThirdUserAuth.SNS_TYPE_QQ,token, expires,openId);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);

                mInfo = new com.tencent.connect.UserInfo(getApplicationContext(), mTencent.getQQToken());

                mInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object o) {
                        JSONObject oo=((JSONObject) o);
                        try
                        {
                            toast("授权F成功");
                            name=oo.getString("nickname");
                            sex=oo.getString("gender").equals("男")?1:0;
                            headUrl=oo.getString("figureurl_2");

                            loginWithAuth(thirdUserAuth);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(UiError uiError) {

                    }

                    @Override
                    public void onCancel() {

                    }
                });


            }
        } catch(Exception e) {
        }
    }
    ;




    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                TencentUtil.showResultDialog(Login_Activity.this, "返回为空", "登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                TencentUtil.showResultDialog(Login_Activity.this, "返回为空", "登录失败");
                return;
            }
           // TencentUtil.showResultDialog(Login_Activity.this, response.toString(), "登录成功");
            // 有奖分享处理
           // handlePrizeShare();
            doComplete((JSONObject)response);
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
            TencentUtil.toastMessage(Login_Activity.this, "onError: " + e.errorDetail);
            TencentUtil.dismissDialog();
        }

        @Override
        public void onCancel() {
            //TencentUtil.toastMessage(Login_Activity.this, "onCancel: ");
            TencentUtil.dismissDialog();
            if (isServerSideLogin) {
                isServerSideLogin = false;
            }
        }
    }




    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                setLoginProgress(50);   //正在登录进度条
                setEditViewEnable(false);  //登录的时候设置不能修改输入框内容
                loginPresent.loginClick();
                break;
            case R.id.btn_register:
                loginPresent.registeClick();
                break;
            case R.id.cb_displaypassword:
                if(checkBox_displayPassword.isChecked()) {
                    //显示明文密码 ，光标设置最后
                    editText_passWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    editText_passWord.setSelection(editText_passWord.getText().length());
                }else{
                    editText_passWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    editText_passWord.setSelection(editText_passWord.getText().length());
                }
                break;
            case R.id.btn_forgetpassword:
                startActivity(ForgetPassWordActivity2.class,null,false);

        }
    }


    @Override
    public Activity getActivity() {
        return Login_Activity.this;
    }

    @Override
    public String getUserName() {
        return editText_userName.getText().toString();
    }

    @Override
    public String getPassWord() {
        return editText_passWord.getText().toString();
    }

    @Override
    public void setLoginClickabel(boolean clickabel,boolean changeProgress) {
        button_login.setClickable(clickabel);
        if(clickabel){
            button_login.setBackgroundColor(Color.parseColor("#0D9BCD"));
            button_login.setTextColor(Color.parseColor("#ffffff"));
        }else{
            if(changeProgress){
                setLoginProgress(0);
            }
            button_login.setBackgroundColor(Color.parseColor("#027CC7"));
            button_login.setTextColor(Color.parseColor("#ffffff"));
        }
    }

    @Override
    public void setLoginProgress(int progress) {
        button_login.setProgress(progress);
    }

    @Override
    public void setEditViewEnable(boolean enbale) {
        editText_passWord.setEnabled(enbale);
        editText_userName.setEnabled(enbale);
    }

    private void findWidgets(){
        checkBox_displayPassword=findViewById(R.id.cb_displaypassword);
        editText_passWord=findViewById(R.id.et_password);
        editText_userName=findViewById(R.id.et_username);
        button_login = findViewById(R.id.btn_login);
        btnForgetPassword=findViewById(R.id.btn_forgetpassword);
        Button button_register = findViewById(R.id.btn_register);
        button_login.setMode(ActionProcessButton.Mode.ENDLESS);
        //注册监听
        button_login.setOnClickListener(this);
        setLoginClickabel(false,true);   //默认不可点击
        button_register.setOnClickListener(this);
        checkBox_displayPassword.setOnClickListener(this);
        btnForgetPassword.setOnClickListener(this);

        //密码输入框监视
        editText_passWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(editText_passWord.getText().toString().equals("")){
                    isPassWdIn=false;
                }else{
                    isPassWdIn=true;
                }

                if(isPassWdIn&&isUserNameIn){
                    setLoginClickabel(true,false);
                }else{
                    setLoginClickabel(false,true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        editText_userName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(isAllSpace(editText_userName.getText().toString())){
                    isUserNameIn=false;
                }else {
                    isUserNameIn=true;
                }
                if(isPassWdIn&&isUserNameIn){
                    setLoginClickabel(true,false);
                }else{
                    setLoginClickabel(false,true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }
}
